<style>
* {
   margin: 0px;
   padding: 0px;
}

.col-marleft {
   display: flex;
   justify-content: space-around;
}

.head_search {
   margin-bottom: 10px;
}
</style>
<template>
   <!-- 头部搜索 -->
   <div class="head_search">
      <el-row>
         <el-col :span="6">
            <div class="text">
               <el-input v-model="search" placeholder="请输入部位名称" />
            </div>
         </el-col>
         <el-col :span="10">
            <!-- 搜索 -->
            <el-button type="primary" plain style="margin-left: 10px;" @click="getDataByName">
               <el-icon>
                  <Search />
               </el-icon>搜索
            </el-button>
            <!-- 打开添加弹窗 -->
            <el-button type="info" @click="Add" plain>
               <el-icon>
                  <Plus />
               </el-icon>添加
            </el-button>
            <!-- 批量删除 -->
            <el-button type="danger" @click="handleDelete(0, 0)" plain>
               <el-icon>
                  <Delete />
               </el-icon>批量删除
            </el-button>
         </el-col>
      </el-row>
   </div>

   <!-- 表格 -->
   <!-- 设置表格中的语言配置为中文 -->
   <el-config-provider :locale="zhCn">
      <el-table :data="tableData" style="width: 100%;" @selection-change="handleSelectionChange">
         <el-table-column type="selection" width="55" />
         <el-table-column label="ID" prop="id" />
         <el-table-column label="部位" prop="bodypart" />
         <el-table-column label="排序ID" prop="orderNum" />
         <el-table-column label="添加时间" prop="create_time" />
         <el-table-column label="操作">
            <template #default="scope">
               <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
               <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
         </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="demo-pagination-block" style="margin-top: 10px;">
         <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50, 100]"
            :background="background" layout="total, sizes, prev, pager, next, jumper" :total="totalNum"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
   </el-config-provider>
   <!-- 添加/编辑Form -->
   <el-dialog v-model="dialogFormVisible" title="添加/修改" width="40%" :before-close="handleClose">
      <el-form :model="form" :label-position="labelPosition" class="demo-form-inline">
         <!-- 科室代码/科室名称-->
         <el-row class="col-marleft">
            <el-col :span="15">
               <el-form-item label="部位">
                  <el-input v-model="form.bodypart" placeholder="请输入部位" />
                  <el-input v-model="form.id" type="hidden" />
               </el-form-item>
            </el-col>
         </el-row>

         <!-- 排序ID/科室类型-->
         <el-row class="col-marleft">
            <el-col :span="15">
               <el-form-item label="排序ID">
                  <el-input-number v-model.orderNum="form.orderNum" style="width: 100%;" :min="0" />
               </el-form-item>
            </el-col>
         </el-row>
      </el-form>
      <template #footer>
         <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="btnSave">
               提交
            </el-button>
         </span>
      </template>
   </el-dialog>
</template>

<script setup >
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElConfigProvider } from 'element-plus'
// 引入中文包
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import axios from 'axios'

// 表格数据
const tableData = ref([])
onMounted(() => {
   binTable(pageSize.value, 1, search.value)
})

//与输入框绑定，获取模糊查询的值
const search = ref('')
//点击查询按钮，调用binTable方法
function getDataByName() {
   binTable(pageSize.value, 1, search.value)
}

//获取添加/编辑表单的值
var form = ref({
   id: 0,
   bodypart: "",
   create_time: getNowDate(),
   orderNum: 0
})
//定义弹出层的状态
var dialogFormVisible = ref(false)
//修改方法
var handleEdit = (index, row) => {
   console.log(row)
   dialogFormVisible.value = true
   //将当前行的数据赋值给表单
   form.value = row
}
//添加方法
function Add() {
   dialogFormVisible.value = true
   form.value = { id: 0, bodypart: "", create_time: getNowDate(), orderNum: 0 }
}

//表单保存，进行添加/编辑操作
function btnSave() {
   axios({
      url: '/api/business/Bodyparts',
      method: form.value.id === 0 ? 'post' : 'put',
      // 请求头
      headers: {
         'content-type': 'application/json'
      },
      data: form.value
   }).then((res) => {
      if (res.data.code == 200) {
         ElMessage({
            message: '保存成功',
            type: 'success',
         });
         // 关闭弹出层
         dialogFormVisible.value = false;
         form.value.id = 0
         //刷新表格
         binTable(pageSize.value, 1, search.value);
      } else {
         ElMessage({
            message: '保存失败',
            type: 'warning',
         })
      }
   })
}

//存储选中的数据的id集合
const ids = ref([])
//获取表格多选按钮选中后的数据id集合
const handleSelectionChange = (val) => {
   // 获取选中行的id组成的数组
   ids.value = val.map(item => item.id);
   console.log(ids.value);
}
//删除方法，通过id删除，可多选删除
var handleDelete = (index, row) => {
   //删除数据的ID
   var id
   ElMessageBox.confirm(
      '确定要删除吗?',
      'Warning',
      {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
      }
   ).then(() => {
      id = row.id > 0 ? row.id : ids.value.join(',');
      axios.delete(`/api/business/Bodyparts/${id}`).then(function (res) {
         if (res.data.code == 200) {
            ElMessage({
               type: 'success',
               message: "删除成功"
            })
            binTable(pageSize.value, 1, search.value);
         } else {
            ElMessage({
               type: 'warning',
               message: "删除失败" + res.data.msg
            })
         }
      }).catch(() => {
         ElMessage({
            type: 'warning',
            message: "删除失败!"
         })
      })
   }).catch(() => {
      ElMessage({
         type: 'info',
         message: '取消删除',
      })
   })
}

// 定义函数binTable，用于获取数据，并进行分页
function binTable(page, pageNum, strName) {
   axios.get(`/api/business/Bodyparts/list?PageNum=${pageNum}&PageSize=${page}&TotalNum=16&TotalPageNum=0&bodypart=${strName}`)
      .then(function (response) {
         tableData.value = response.data.data.result;
         currentPage.value = response.data.data.pageIndex;
         totalNum.value = response.data.data.totalCount;
         console.log(response.data.data.result)
      })
}

//获取当前时间
function getNowDate() {
   const now = new Date();
   const year = now.getFullYear();
   const month = ('0' + (now.getMonth() + 1)).slice(-2);
   const day = ('0' + now.getDate()).slice(-2);
   const hours = ('0' + now.getHours()).slice(-2);
   const minutes = ('0' + now.getMinutes()).slice(-2);
   const seconds = ('0' + now.getSeconds()).slice(-2);
   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

//定义获取到的数据总行数
const totalNum = ref()
// 定义当前页数和每页显示条数的变量
const currentPage = ref(1)
const pageSize = ref(5)
// 定义背景颜色变量
const background = ref(true)
// 定义每页显示条数改变事件
const handleSizeChange = (val) => {
   binTable(val, currentPage.value, search.value)
}
// 定义当前页数改变事件
const handleCurrentChange = (val) => {
   binTable(pageSize.value, val, search.value)
}
</script>